import G6 from "@antv/g6";
import AGVKX from "./assets/icons/svg/robot.svg";
import Charging from "./assets/icons/svg/charging.svg";
import LowElectricity from "./assets/icons/svg/lackOfPower.svg";
import Fault from "./assets/icons/svg/Fault.svg";
// 升级后的图标
import Resting from "./assets/icons/svg/rcs_icons_resting_color.svg"; //休息
import Interaction from "./assets/icons/svg/rcs_icons_interaction_color.svg"; //交汇
import Restrict from "./assets/icons/svg/rcs_icons_restrict_color.svg"; //禁行
import Rotation from "./assets/icons/svg/rcs_icons_rotation_color.svg"; //旋转
import GoodsShelves from "./assets/icons/svg/shelves4.svg";// 货架

//获取电池颜色
function getBattery(num) {
  // "#cd901b", //黄色, "#066f65", //绿色 ,"#0188b6", //蓝色
  if (Number(num) >= 80) {
    return "#0188b6";
  } else if (Number(num) < 80 && Number(num) >= 40) {
    return "#066f65";
  } else {
    return "#cd901b";
  }
}
//自定义节点状态
/**
 * @description 车节点
 * */
export const useCustomAGVCar = (graph = null) => {
  G6.registerNode("car-node", {
    draw(cfg, group) {
      // console.log("小车节点-draw", cfg, group);
      let robotId = cfg.id.substring(4); //机器人ID
      //机器人ID文本
      group.addShape("text", {
        attrs: {
          textAlign: "end",
          y: -14,
          fontSize: 10,
          text: robotId,
          fill: "#28383c"
        },
        name: `label-${robotId}`
      });

      //小车 CarOffline
      const size = 28;
      const width = size;
      const height = size;
      const image = group.addShape("image", {
        attrs: {
          x: -width / 2,
          y: -height / 2,
          width,
          height,
          img: AGVKX
        },
        name: `image-car-${robotId}`
      });

      //电量
      const battery = group.addShape("rect", {
        attrs: {
          x: 3,
          y: -24,
          width: 16,
          height: 8,
          stroke: getBattery(cfg.battery),
          radius: [2]
        },
        name: `battery-rect-${robotId}`
      });
      group.addShape("text", {
        attrs: {
          x: 5,
          y: -17,
          fontSize: 5,
          text: cfg.battery ? `${cfg.battery}%` : "0%",
          fill: "#28383c"
        },
        name: `battery-text-${robotId}`
      });

      //货架
      const shelfSize = 16;
      const goodsShelves = group.addShape("image", {
        attrs: {
          x: -shelfSize / 2,
          y: -shelfSize / 2,
          width: shelfSize,
          height: shelfSize,
          img: GoodsShelves
        },
        name: `image-goodsShelves-${robotId}`,
        visible: cfg.hasShelf ? true : false
        // visible: isVisible
      });

      //隐藏货架图形
      // if (parentNode.hasShelf && !cfg.hasShelf) {
      //   goodsShelves.attr("opacity", 0.4);
      // } else {
      //   goodsShelves.attr("opacity", 1);
      // }

      //充电
      const chargingSize = 20;
      const chargingImg = group.addShape("image", {
        attrs: {
          x: -chargingSize / 2,
          y: -chargingSize / 2,
          width: chargingSize,
          height: chargingSize,
          img: Charging
        },
        name: `image-Charging-${robotId}`,
        visible: cfg.isCharge ? true : false
      });

      //缺电
      const electricitySize = 20;
      const electricityImg = group.addShape("image", {
        attrs: {
          x: -electricitySize / 2,
          y: -electricitySize / 2,
          width: electricitySize,
          height: electricitySize,
          img: LowElectricity
        },
        name: `image-electricity-${robotId}`,
        visible: cfg.isLOP ? true : false
      });

      //故障
      const faultSize = 20;
      const faultImg = group.addShape("image", {
        attrs: {
          x: -faultSize / 2,
          y: -faultSize / 2 - 2,
          width: faultSize,
          height: faultSize,
          img: Fault
        },
        name: `image-fault-${robotId}`,
        visible: cfg.isFault ? true : false
      });

      // 绘制雷达波效果
      const radarWaves = [];
      for (let i = 0; i < 4; i++) {
        radarWaves.push(
          group.addGroup().addShape("circle", {
            attrs: {
              x: 0,
              y: 0,
              r: 0, // 初始半径为 0
              stroke: "#40a9ff",
              lineWidth: 2,
              opacity: 0.5 - i * 0.1 // 不同波浪的透明度递减
            },
            name: `radar-shape-${robotId}-${i}`,
            visible: cfg.isBlock ? true : false
          })
        );
      }

      // 添加动画，让雷达波效果扩散
      radarWaves.forEach((wave, index) => {
        wave.animate(
          {
            r: 50 + index * 10, // 不同波浪的半径递增
            opacity: 0 // 动画结束时透明度变为 0
          },
          {
            repeat: true, // 重复动画
            duration: 2000, // 动画时长
            easing: "easeCubicIn", // 缓动函数
            delay: index * 400 // 不同波浪之间的动画延迟
          }
        );
      });

      // console.log("车图片", image, group, cfg);
      // let matrix = image.getMatrix();
      // // 图形或分组的初始矩阵时 null，为了避免变换一个 null 矩阵，需要将其初始化为单位矩阵
      // if (!matrix) matrix = [1, 0, 0, 0, 1, 0, 0, 0, 1];
      // // 矩阵变换，用于二维渲染
      // const newMatrix = Util.transform(matrix, [
      //   ["r", nodeDirection(cfg.direction)] // rotate
      // ]);
      // image.setMatrix(newMatrix);

      const degrees = cfg.degrees || 0; // 获取度数，默认为 0
      image.rotate((degrees * Math.PI) / 180); // 将度数转换为弧度并进行旋转

      return image;
    },
    update(cfg, node) {
      const group = node.getContainer();
      const keyShape = node.getKeyShape(); // 获取节点的形状
      // console.log("小车节点-update", cfg.battery, group);

      // 设置节点的旋转角度（单位为弧度）
      // let matrix = keyShape.getMatrix();
      // // 图形或分组的初始矩阵时 null，为了避免变换一个 null 矩阵，需要将其初始化为单位矩阵
      // if (!matrix) matrix = [1, 0, 0, 0, 1, 0, 0, 0, 1];
      // // 矩阵变换，用于二维渲染
      // const newMatrix = Util.transform(matrix, [
      //   ["r", nodeDirection(cfg.direction)] // rotate
      // ]);
      // keyShape.setMatrix(newMatrix);

      //旋转方案2
      // keyShape.resetMatrix();
      // const degrees = cfg.degrees || 0; // 获取度数，默认为 0
      // keyShape.rotate((degrees * Math.PI) / 180); // 将度数转换为弧度并进行旋转

      //旋转方案3
      if (cfg.isRotate) {
        let matrix = keyShape.getMatrix();
        if (!matrix) {
          matrix = [1, 0, 0, 0, 1, 0, 0, 0, 1];
          cfg.oldDegrees = 0;
        } else {
          let degreeNum = Math.round((Math.atan2(matrix[1], matrix[0]) * 180) / Math.PI);
          //角度不为0、90、180、270时重置角度为0
          if (degreeNum != cfg.oldDegrees && degreeNum != -90 && cfg.oldDegrees != 270) {
            matrix = [1, 0, 0, 0, 1, 0, 0, 0, 1];
            cfg.oldDegrees = 0;
          }
        }

        const degrees = cfg.degrees || 0; // 获取度数，默认为 0
        const oldDegrees = cfg.oldDegrees || 0; // 获取度数，默认为 0
        cfg.isRotate = false; //重置旋转状态,默认是false

        keyShape.animate(
          (ratio) => {
            let angleNumber;
            if (oldDegrees == 270 && degrees == 0) {
              angleNumber = 90;
            } else if (oldDegrees == 0 && degrees == 270) {
              angleNumber = -90;
            } else {
              angleNumber = degrees - oldDegrees;
            }
            const angle = (angleNumber * Math.PI) / 180; // 将度数转换为弧度并进行旋转
            const newAngle = angle * ratio;
            let newMatrix = G6.Util.transform(matrix, [
              ["r", newAngle] // 旋转
            ]);

            return {
              matrix: newMatrix
            };
          },
          {
            repeat: false,
            duration: cfg.rotateTime ? Number(cfg.rotateTime) : 100, //400
            easing: "easeLinear",
            callback: function () { }
          }
        );
      }

      //移动方案1
      if (cfg.matrix) {
        group.animate(
          {
            matrix: cfg.matrix //坐标变换
          },
          {
            repeat: false,
            duration: cfg.moveTime ? Number(cfg.moveTime) : 500, //260
            easing: "easeLinear",
            callback: function () {
              if (node.getModel().matrix) {
                node.getModel().x = node.getModel().matrix[6]; //修改横坐标
                node.getModel().y = node.getModel().matrix[7]; //修改纵坐标
              }
            }
          }
        );
      }

      //隐藏货架图形
      const child = group.find((item) => {
        return item.cfg.name.includes("image-goodsShelves");
      });

      if (!child) return;
      const parentNode = graph.value.findById(cfg.parentNode).getModel();
      // let isVisible = cfg.hasShelf || parentNode.hasShelf;
      let isVisible = cfg.hasShelf;
      child.cfg.visible = isVisible;

      // if (parentNode.hasShelf && !cfg.hasShelf) {
      //   child.attr("opacity", 0.4);
      // } else {
      //   child.attr("opacity", 1);
      // }
      //电量
      const batteryRect = group.find((item) => {
        return item.cfg.name.includes("battery-rect");
      });
      batteryRect.attr("stroke", getBattery(cfg.battery));

      const batteryText = group.find((item) => {
        return item.cfg.name.includes("battery-text");
      });

      let batteryNum = cfg.battery ? `${cfg.battery}%` : "0%";
      batteryText.attr("text", batteryNum);
    }
  });
};
const NodeDesEnum ={
  1:"#FFFFFF" , //路径点
  2: "#c2c2c2", //存储点
  4:"#FFC14D", //充电点
  6:"#00B8D4" //工作站
}
//返回图标
function getIcon(type) {
  if (type == 1) {
    return Resting;
  } else if (type == 2) {
    return Interaction;
  } else if (type == 3) {
    return Restrict;
  } else if (type == 4) {
    return Rotation;
  } else if (type == 9) {
    return GoodsShelves;
  }
}

//设置属性图标
function setAttrIcon(cfg, group) {
  const size = 16;
  const width = size;
  const height = size;
  //nodeAttrs是数组
  let { nodeAttrs, hasShelf } = cfg;
  const attrIcons = [1, 2, 3, 4]; //['休息','交汇','禁行','旋转']
  let sameAtt = null;
  //有货架优先显示货架
  if (hasShelf) {
    sameAtt = 9;
  } else {
    sameAtt = nodeAttrs.find((item) => {
      return attrIcons.includes(item);
    });
  }
  let shapeName = `icon-shape-${cfg.id}`;
  // 第一次看：ImageShape是undefined
  let ImageShape = group.get("children").find((item) => {
    return item?.cfg?.name == shapeName;
  });
  //属性为空时删除之前创建的图形
  if (!sameAtt && ImageShape) return group.removeChild(ImageShape);
  if (!sameAtt) return;

  if (!ImageShape) {
    //创建图形
    group.addShape("image", {
      attrs: {
        x: -width / 2,
        y: -height / 2,
        width,
        height,
        img: getIcon(sameAtt)
      },
      name: shapeName
    });
  } else {
    //修改图形img
    ImageShape.attr("img", getIcon(sameAtt));
  }
}

//获取节点xy坐标
function getNodeXY(direction) {
  //上(0,-10)，下(0,10)，左(-10,0)，右(10,0)
  if (direction == 0) {
    return { x: 0, y: -10 };
  } else if (direction == 180) {
    return { x: 0, y: 10 };
  } else if (direction == 270) {
    return { x: -10, y: 0 };
  } else if (direction == 90) {
    return { x: 10, y: 0 };
  } else {
    return { x: 0, y: 0 };
  }
}

//设置方向点位
function setDirection(cfg, group) {
  let shapeName = `direction-shape-${cfg.id}`;
  let directionShape = group.get("children").find((item) => {
    return item?.cfg?.name == shapeName;
  });

  //方向为空，之前有节点，删除之前的节点
  if (cfg.direction === "" && directionShape) return group.removeChild(directionShape);

  if (cfg.direction === "" || cfg.direction == null) return;

  if (!directionShape) {
    //方向不为空，之前也没节点，新增节点方向
    const shape = group.addShape("circle", {
      attrs: {
        fill: "red",
        r: 2.5,
        x: 0,
        y: 0
      },
      name: shapeName
    });

    let { x, y } = getNodeXY(cfg.direction);
    shape.attr("x", x);
    shape.attr("y", y);
  } else {
    //方向不为空，之前有节点，修改节点方向
    let { x, y } = getNodeXY(cfg.direction);
    directionShape.attr("x", x);
    directionShape.attr("y", y);
  }
}

//根据节点类型设置节点颜色
function setNodeFill(cfg, shape) {
  if (cfg.nodeType == 1) {
    //路径点
    shape.attr("fill", NodeDesEnum[1]);
  } else if (cfg.nodeType == 2) {
    //存储点
    shape.attr("fill", NodeDesEnum[2]);
  } else if (cfg.nodeType == 4) {
    //充电点
    shape.attr("fill", NodeDesEnum[4]);
  } else if (cfg.nodeType == 6) {
    //工作站
    shape.attr("fill", NodeDesEnum[6]);
  }
}

export const usePathNodeUpgrade = () => {
  G6.registerNode(
    "path-upgrade-node",
    {
      afterDraw(cfg, group) {
        //设置属性图标
        setAttrIcon(cfg, group);
        //设置节点方向
        setDirection(cfg, group);
        //根据节点类型设置节点颜色
        const shape = group.get("children")[0]; // 获取节点的 shape
        setNodeFill(cfg, shape);
      },
      afterUpdate(cfg, item) {
        const group = item.getContainer();
        // //设置属性图标
        setAttrIcon(cfg, group);
        //设置节点方向
        setDirection(cfg, group);

        // //根据节点类型设置节点颜色
        const shape = item.get("keyShape"); // 获取节点的 keyShape
        setNodeFill(cfg, shape);
      },
    },
    "circle"
  );
};

